package com.xoms.front.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.internal.util.AlipaySignature;
import com.xoms.front.controller.res.BaseResult;
import com.xoms.front.service.PayService;
import com.xoms.front.service.exception.ServiceException;
import com.xoms.front.util.pay.ali.AliPayManager;
import com.xoms.front.util.pay.wx.WXPayManager;
import com.xoms.util.StringUtil;

/**
 * 支付处理
 */
@Controller
@RequestMapping(value = "/app/pay", produces = "application/json")
public class SAPPPayController {

	private static Logger logger = Logger.getLogger(SAPPPayController.class);

	@Autowired
	PayService payServiceImpl;

	/**
	 * 微信app支付-异步通知
	 * 
	 * @param request
	 */
	@RequestMapping("/wechatPayCallback")
	public void wechatPayCallback(HttpServletRequest request, HttpServletResponse response) {
		try {
			try {
				String resStr = StringUtil.streamToString(request.getInputStream());
				logger.info("WXPay callback param ========:" + resStr);
				String res = payServiceImpl.wechatPayCallback(resStr);
				if (res != null) {
					response.getWriter().write(res);
				}
			} catch (ServiceException e) {
				logger.error(e.getMessage(), e);
				response.getWriter().write(WXPayManager.getInstance().return2WXFail(null));
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				response.getWriter().write(WXPayManager.getInstance().return2WXFail(null));
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	/**
	 * 支付宝app支付-异步通知
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/aliPayCallback")
	public void aliPayCallback(HttpServletRequest request, HttpServletResponse response) {
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		System.out.println("alipay callback param ==============================" + params);
		// {gmt_create=2018-05-28 17:32:55, charset=UTF-8,
		// seller_email=lingjianping@mymovies.com.cn, subject=烟酒,
		// sign=AEt0xuhNgB7syX0aYMmmvkej7XsGHgExQZS6T/z3fk0r0RjshPCERHiU80+Ob1MUFZ3cW3+y4amX8V6SjNBEMT/gFFjxUEBizYPQCtDQPgLxT0bkH686U/OZfb0z9gP8t8POEkVNkl0Lc2u884KeJ3TxFVj25f0EyC/g3lKl/XYGn5s5INweW8o1WWodHqN7/U3pqsWSJPbiaGrWZOW7l5opPXoqZT5nkkjuVsAg9ug7CxUgyjzA6/gBwYwJsqnARCZgAt0AluFejZad1Zjnkgo4eZ81UEZaek577Cg3e9/7cXXNWFkw+vldkY5kn4WZBO6itCqf87mFx3a11/zUzA==,
		// buyer_id=2088702526244871, invoice_amount=0.01,
		// notify_id=0990abff85e438d503dba7c7a95dfbfmpt,
		// fund_bill_list=[{"amount":"0.01","fundChannel":"PCREDIT"}],
		// notify_type=trade_status_sync,
		// trade_status=TRADE_SUCCESS, receipt_amount=0.01, buyer_pay_amount=0.01,
		// app_id=2018042302593439,
		// sign_type=RSA2, seller_id=2088031725425535, gmt_payment=2018-05-28 17:33:11,
		// notify_time=2018-05-28 17:33:11, version=1.0, out_trade_no=20150320010101020,
		// total_amount=0.01,
		// trade_no=2018052821001004870590318008, auth_app_id=2018042302593439,
		// buyer_logon_id=229***@qq.com, point_amount=0.00}
		try {
			try {
				// 验签
				boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayManager.getAlipayPublicKey(),
						AliPayManager.getCharset(), AliPayManager.getSigntype());
				System.out.println(
						"alipay callback param signVerified =====================>signVerified:" + signVerified);
				if (signVerified) {
					// 验签成功则继续业务操作，最后在response中返回success
					String res = payServiceImpl.aliPayCallback(params);
					if (res != null) {
						response.getWriter().write(res);
					}
				} else {
					// 验签失败则记录异常日志，并在response中返回failure.
					response.getWriter().write(AliPayManager.getInstance().getPayResponseFail());
				}
			} catch (ServiceException e) {
				logger.error(e.getMessage(), e);
				response.getWriter().write(AliPayManager.getInstance().getPayResponseFail());
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				response.getWriter().write(AliPayManager.getInstance().getPayResponseFail());
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}

	}

	/**
	 * 支付宝服务商网关
	 **/
	@RequestMapping("/alipayGateway")
	@ResponseBody
	public BaseResult alipayGateway(HttpServletRequest request, HttpServletResponse response) {
		BaseResult result = new BaseResult();

		return result;
	}

	/**
	 * 支付宝授权回调地址
	 **/
	@RequestMapping("/alipayAuthCallback")
	@ResponseBody
	public BaseResult alipayAuthCallback(HttpServletRequest request, HttpServletResponse response) {
		BaseResult result = new BaseResult();

		return result;
	}

	/**
	 * 支付宝沙箱服务商网关
	 **/
	@RequestMapping("/alipaySandboxGateway")
	@ResponseBody
	public BaseResult alipaySandboxGateway(HttpServletRequest request, HttpServletResponse response) {
		BaseResult result = new BaseResult();

		return result;
	}

	/**
	 * 支付宝沙箱授权回调地址
	 **/
	@RequestMapping("/alipaySandboxAuthCallback")
	@ResponseBody
	public BaseResult alipaySandboxAuthCallback(HttpServletRequest request, HttpServletResponse response) {
		BaseResult result = new BaseResult();

		return result;
	}

}
